﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.ComponentModel;
using MVCApplication.Helpers;
using System.Data;

namespace MVCApplication.Controllers
{
    public class CommonController : Controller
    {
        protected const int GridPageSize = 5;

        public ActionResult Return()
        {
            string url = UrlHistory.BackUrl(Session);
            if (url != null)
            {
                return Redirect(url);
            }
            else
            {
                return RedirectToAction("WorkWith");
            }
        }

        protected void AsignBlobIfBrowsed(string fileName, DataRow row, string columnName)
        {
            System.Web.HttpPostedFileBase file = this.Request.Files[fileName];
            if (file.ContentLength > 0)
            {
                byte [] blob = new byte[file.ContentLength];
                file.InputStream.Read(blob, 0, file.ContentLength);
                row[columnName] = blob;
            }
        }

        public ActionResult GetImage(string dsKey, string tableName, string columnName, int rowIndex, string mimeType)
        {
            DataSet ds = ((DataSet)(Session[dsKey]));
            System.IO.Stream stream = System.IO.MemoryStream.Null;
            DataTable dt = ds.Tables[tableName];
            if(dt.Rows.Count > rowIndex && !dt.Rows[rowIndex].IsNull(columnName))
            {
                stream = new System.IO.MemoryStream((byte[])dt.Rows[rowIndex][columnName]);
            }
            return new FileStreamResult(stream, mimeType);
        }

        protected static int GetCurrentPage(int totalRecords, int currentPage)
        {
            if (currentPage > 1 && (currentPage - 1) * GridPageSize >= totalRecords)
            {
                currentPage = ((totalRecords - 1) / GridPageSize) + 1;
            }
            return currentPage;
        }

        protected void InstantiateAttributes(DataRow row, string instantiatedAttributes)
        {
            string[] splitted = GeneralFunctions.GetSplittedText(instantiatedAttributes);
            if (splitted != null)
            {
                for (int i = 0; i < splitted.Length - 1; i = i + 2)
                {
                    string attributeName = splitted[i];
                    string attributeValue = splitted[i + 1];
                    if (row.Table.Columns.Contains(attributeName))
                    {
                        DataSetHelper.SetRowValue(row, attributeName, attributeValue);
                    }
                }
                SetReadOnlyToInstantiateAttributes(splitted);
            }
        }

        protected void SetReadOnlyToInstantiateAttributes(string instantiatedAttributes)
        {
            string[] splitted = GeneralFunctions.GetSplittedText(instantiatedAttributes);
            if (splitted != null)
            {
                SetReadOnlyToInstantiateAttributes(splitted);
            }
        }

        private void SetReadOnlyToInstantiateAttributes(string[] splitted)
        {
            for (int i = 0; i < splitted.Length - 1; i = i + 2)
            {
                ViewData["ReadOnly_" + splitted[i]] = true;
            }
        }

        protected ActionResult CreateRelatedAction(string controllerName, string[] pk, System.Data.DataRow row, string[] pkNames)
        {
            string instantiatedAttributesValue = GetColumnValuesFromatedString(pk, pkNames, true, row);
            return RedirectToAction("Create", controllerName, new { instantiatedAttributes = instantiatedAttributesValue });
        }

        protected ActionResult DisplayRelatedAction(string controllerName, System.Data.DataRow row, string[] pkNames, string fillByMethodName)
        {
            string filterValuesString = GetColumnValuesFromatedString(null, pkNames, false, row);
            return RedirectToAction("WorkWith", controllerName, new { fillByMethod = fillByMethodName, filterValues = filterValuesString });
        }

        private static string GetColumnValuesFromatedString(string[] cols, string[] colNames, bool appendName, System.Data.DataRow row)
        {
            if ((cols == null && appendName) || colNames == null || row == null)
            {
                return "";
            }
            System.Text.StringBuilder pkValue = new System.Text.StringBuilder();
            int index = 0;
            foreach (string pkKey in colNames)
            {
                foreach (System.Data.DataColumn rowCol in row.Table.Columns)
                {
                    if (pkKey == rowCol.ColumnName)
                    {
                        if (appendName)
                        {
                            pkValue.Append("-,-" + cols[index]);
                        }
                        pkValue.Append("-,-" + row[rowCol.ColumnName].ToString().Replace(",", ",,"));
                        break;
                    }
                }
                index++;
            }
            if (pkValue.Length > 0)
                return pkValue.ToString().Substring(3);
            else
                return "";
        }
    }
}